#-*- encoding: utf-8 -*-

"""
Yahoo Finance API - Historical Quote
Read Stock Historical Quote, this module just supports shanghai and shenzhen market.

"""

import urllib.request
import urllib.response
import urllib.error
import re
import datetime
from decimal import *

import data.QuoteData
from data.YFACommon import *



def parseIds(ids):
    # 检查输入参数，如果已经是列表，则检查每个列表项并返回，如果是字符串，分隔符解析并转换为字符串
    if ids==None:
        return None

    idList = None
    if type(ids) is str:
        # ids是字符串类型，需要用分隔符解析
        vals = ids.split(",")
        idList = []
        for id in vals:
            if id==None or id=="":
                continue
            idList.append(checkStockCode(id.strip()))

    elif type(ids) is list:
        idList = []
        for id in ids:
            idList.append(checkStockCode(id.strip()))
    else:
        pass

    return idList

def readHisData(id, fromYear, fromMonth, fromDay, toYear, toMonth, toDay):
    params = {KEY_IDS: id, KEY_FROMDATE_YEAR: fromYear, KEY_FROMDATE_MONTH: fromMonth, KEY_FROMDATE_DAY: fromDay, KEY_TODATE_YEAR: toYear, KEY_TODATE_MONTH: toMonth, KEY_TODATE_DAY: toDay, KEY_HIS_FORMAT: VALUE_FORMAT_CSV}
    quoteUrl = BASE_HIS_URL+"?"+urllib.parse.urlencode(params)
    print("historical url:", quoteUrl)

    props = None
    try:
        f = urllib.request.urlopen(quoteUrl)
        line = f.readline()
        quotes = []
        while len(line)>0:
            line = str(line, "UTF-8")
            #print(line)

            if props==None:
                props = []
                values = line.strip().split(",")
                for val in values:
                    props.append(val)
            else:
                quote = data.QuoteData.HisQuote()
                values = line.strip().split(",", len(props)-1)
                index = 0
                for val in values:
                    if props[index]=="Date":
                        quote.date = val
                    elif props[index]=="Open":
                        quote.open = Decimal(val)
                    elif props[index]=="High":
                        quote.high = Decimal(val)
                    elif props[index]=="Low":
                        quote.low = Decimal(val)
                    elif props[index]=="Close":
                        quote.close = Decimal(val)
                    elif props[index]=="Volume":
                        quote.volume = int(val)
                    elif props[index]=="Adj Close":
                        pass
                        #quote.prev = Decimal(val)

                    index += 1

                quotes.append(quote)
                print(quote)
                
            
            line = f.readline()

    except urllib.error.URLError as ue:
        print("Error: ", ue)

def YFAHisData(ids, startDate=None, endDate=None):
    """ 使用Yahoo Finance API读取指定股票的历史数据，默认读取最近1年的数据 """
    idList = parseIds(ids)

    if idList == None:
        return None

    fromYear = 1990
    fromMonth = 11
    fromDay = 1
    today = datetime.date.today()
    toYear = today.year
    toMonth = today.month-1
    toDay = today.day

    hisData = []
    for id in idList:
        readHisData(id, fromYear, fromMonth, fromDay, toYear, toMonth, toDay)
    
